var Groups = {

    selected_row_id : null,
    /* dataTable Object */
    objGrid: null,

    /* Function init
     * @param void
     * @return void
     * @access public
     * */
    init:function(){
        var self = this;
        /*Sortable Table */
        var oTable = null;
        var dataUrl = $('#group-table-url').val();

        self.objGrid = $('#groupflex').flexigrid({
            url: dataUrl,
            dataType: 'json',
            colModel : [
                {display: 'ID', name : 'id', width : 20, sortable : false, align: 'left', hide:true},
                {display: 'Group Name', name : 'name', width : 280, sortable : true, align: 'center', hide:false},
                {display: 'Active', name : 'active', width : 180, sortable : true, align: 'center', hide:false}
            ],
            formFields : [
                {type:'buttom',name: 'Add', bclass: 'add', onpress : self.handleGridEvent},
                {separator: true},
                {type:'buttom',name: 'Edit', bclass: 'edit', onpress : self.handleGridEvent},
                {separator: true},
                {type:'buttom',name: 'Delete', bclass: 'delete', onpress : self.handleGridEvent}
            ],
            searchitems : [
                {display: 'Group Name', name : 'name', isdefault: true}
            ],
            checkboxSelection: true,
            columnControl:true,
            sortname: "id",
            sortorder: "desc",
            usepager: true,
            title: 'Groups',
            useRp: true,
            rp: 15,
            showTableToggleBtn: false,
            height: 300
        });

        $('#save-btn').click(function(){
            self.saveGroup();
        });

        $('#cancel-btn').click(function(){
            document.getElementById('group-form').reset();
            var modules_count = $('#modules_count_id').val();
            for(var x = 0; x < modules_count; x++){
                $('#group-form-window #group-form #ModulesGroup'+x+'ModuleId').attr('checked',false);
            }
            $.validationEngine.closePrompt('.formError',true);
            $.colorbox.close();
            self.selected_row_id = null;
        });

        jLib.afterClosePopUpForm('group-form',function(){
            self.selected_row_id = null;
            document.getElementById('group-form').reset();
            var modules_count = $('#modules_count_id').val();
            for(var x = 0; x < modules_count; x++){
                $('#group-form-window #group-form #ModulesGroup'+x+'ModuleId').attr('checked',false);
            }
        });

        $("#group-form").validationEngine();
    },

    handleGridEvent: function(com, grid){
        if (com == 'Add') {
            $.colorbox({
                inline:true,
                scrolling:false,
                overlayClose:false,
                escKey:false,
                title:'Group Information',
                href:"#group-form-window"
            });
        }
        else if (com == 'Edit') {
            if(jLib.rowSelectedCheck(grid,1)){
                Groups.editGroup(jLib.getSelectedRowIds(grid));
            }
        }
        else if (com == 'Delete') {
            if(jLib.rowSelectedCheck(grid)){
                Groups.deleteGroup(grid);
            }
        }
    },

    editGroup:function(row_ids){
        var self = this;
        var groupID = row_ids[0];
        var url = $('#load-group-url').val();
        var query = 'type=load&group-id=' + groupID;
        $.ajax({
            url:url,
            data:query,
            dataType:'json',
            type:'POST',
            success:function (response) {
                var txt = '';
                if (typeof response.mesg == 'object') {
                    for (megTxt in response.mesg) {
                        txt += response.mesg[megTxt] + '<br />';
                    }
                }
                else {
                    txt = response.mesg
                }
                //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*
                if (response.code === 0) {
                    var dataGroup = response.data.Group;
                    var dataModules = response.data.Module;
                    var modules_count = $('#modules_count_id').val();
                    $('#group-form-window #group-form #name').val(dataGroup.name);
                    $('#group-form-window #group-form #active').val(dataGroup.active);
                    $('#group-form-window #group-form #active').change();

                    for(var x = 0; x < modules_count; x++){
                        var value = $('#group-form-window #group-form #ModulesGroup'+x+'ModuleId').val();
                        if(jQuery.inArray(value, dataModules) > -1){
                            $('#group-form-window #group-form #ModulesGroup'+x+'ModuleId').attr('checked','checked');
                        }
                    }

                    self.selected_row_id = groupID;

                    $.colorbox({
                        inline:true,
                        scrolling:false,
                        overlayClose:false,
                        escKey:false,
                        title:'Group Information',
                        href:"#group-form-window"
                    });
                }
                //* When there are Errors *//*
                else if (response.code === 1) {
                    jLib.serverError(txt);
                }
            },
            error:function (xhr) {
                console.log(xhr.responseText);
                jLib.serverError();
            }
        });
    },

    saveGroup:function(){
        var self = this;
        /* Validate the form*/
        var validationStatus =  $('#group-form').validationEngine({returnIsValid:true});
        /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
        if(validationStatus){
            jLib.showFormLoading();
            var query = 'model=Group&row_id='+self.selected_row_id+'&'+ $('#group-form').serialize();
            var url = $("#group-add-edit-url").val();
            /* Send the data to the server and handle the server response */
            $.ajax({
                url:url,
                data:query,
                dataType:'json',
                type:'POST',
                success:function (response) {
                    var txt = '';
                    if (typeof response.mesg == 'object') {
                        for (megTxt in response.mesg) {
                            txt += response.mesg[megTxt] + '<br />';
                        }
                    }
                    else {
                        txt = response.mesg
                    }
                    jLib.hideFormLoading();
                    //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*
                    jLib.message(txt, 'success');

                    if (response.code === 0) {
                        if(self.selected_row_id){
                            // Chnge the cell data
                            var update_data = {
                                'name': $('#group-form-window #group-form #name').val(),
                                'active': $('#group-form-window #group-form #active').val() == 'y' ? 'Active' : 'Inactive'
                            };
                            jLib.updateGridData(self.objGrid, update_data);
                            jLib.highlightRow(self.objGrid);
                        }
                        else{
                            $(self.objGrid).flexReload();
                        }
                        document.getElementById('group-form').reset();
                        $.validationEngine.closePrompt('.formError',true)
                        $.colorbox.close();
                        self.selected_row_id = null;

                    }
                    //* When there are Errors *//*
                    else if (response.code === 1) {
                        jLib.serverError(txt);
                    }
                },
                error:function (xhr) {
                    console.log(xhr.responseText);
                    jLib.serverError();
                }
            });
        }
    },


    deleteGroup:function(grid){
        var self = this;
        var url = $('#group-delete-url').val();
        jLib.do_delete(url,grid);
    }

};


/* when the page is loaded */
$(document).ready(function() {
    Groups.init();
});